package com.blueocean_health.care.management.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.jsoup.Connection.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.blueocean_health.care.management.common.LocalManager;
import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.base.User;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoDto;
import com.blueocean_health.care.management.domain.dto.NurseWorkerInfoRequestDto;
import com.blueocean_health.care.management.em.LocalManagerType;
import com.blueocean_health.care.management.util.JsoupUtils;

@RestController
@RequestMapping("/web/nurse")
public class NurseWorkerInfoController {

	@Value("${nurse.service.address}")
	private String nurseServiceAddress = "http://127.0.0.1:11005";

	/**
	 * 更新护工表中所有护工拼音字段
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/update-workername-pinyin")
	public SysResult updateWorkernamePinyin() throws IOException {
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/update-workername-pinyin", null);
	}

	/**
	 * 新建护工
	 * 
	 * @param nurseWorkerInfo
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/add")
	public SysResult add(@RequestBody @Valid NurseWorkerInfoDto nurseWorkerInfoDto) throws IOException {
		// 获得当前登录用户信息
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoDto.setHospital(user.getHospitalId());
		nurseWorkerInfoDto.setHospitalName(user.getHospitalName());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/save", nurseWorkerInfoDto);
	}

	/**
	 * 修改护工基本信息
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/modify")
	public SysResult modify(@RequestBody @Valid NurseWorkerInfoDto nurseWorkerInfoDto) throws IOException {
		// 获得当前登录用户信息
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoDto.setHospital(user.getHospitalId());
		nurseWorkerInfoDto.setHospitalName(user.getHospitalName());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/update", nurseWorkerInfoDto);
	}

	/**
	 * 删除护工
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/delete")
	public SysResult delete(@RequestBody NurseWorkerInfoDto nurseWorkerInfoDto) throws IOException {
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/delete", nurseWorkerInfoDto);
	}

	/**
	 * 获取护工详情
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/query")
	public SysResult findDetail(@RequestBody NurseWorkerInfoDto nurseWorkerInfoDto) throws IOException {
		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoDto.setHospital(courrentUser.getHospitalId());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/query", nurseWorkerInfoDto);
	}

	/**
	 * 获取护工列表分页
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/list")
	public SysResult findList(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto) throws IOException {
		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoRequestDto.setTeamId(courrentUser.getHospitalId());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/list", nurseWorkerInfoRequestDto);
	}

	/**
	 * 上传图片
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/img/upload")
	public SysResult upload(@RequestParam(value = "img") MultipartFile imgFile) throws Exception {
		String url = nurseServiceAddress + "/nurse/img/upload";
		return JsoupUtils.doPostFileRequestToSysResult(url, null, imgFile, "img");
	}

	/**
	 * 导出护工Execl
	 */
	@RequestMapping("/exportNurseWorkerInfoExcel")
	public void listNurseWorkerInfoExecl(NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto,
			HttpServletResponse response) {
		OutputStream toClient = null;
		try {
			User user = LocalManager.getVal(LocalManagerType.USER_WEB);
			nurseWorkerInfoRequestDto.setTeamId(user.getHospitalId());
			Response fileResponse = JsoupUtils.doPostFileResponse(
					nurseServiceAddress + "/nurse/exportNurseWorkerInfoExcel", nurseWorkerInfoRequestDto);
			String finalFileName = URLEncoder.encode("护工列表_" + TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS) + ".xls",
					"UTF8");
			response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
			toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(fileResponse.bodyAsBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				toClient.flush();
				toClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 下载模板
	 * @return 
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/exportTemplateExcel")
	public ResponseEntity<byte[]> exportTemplateExcel(HttpServletResponse response, HttpServletRequest request) throws IOException {
		try {
			Response fileResponse = JsoupUtils.doPostFileResponse(nurseServiceAddress + "/nurse/exportTemplateExcel",
					null);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", URLEncoder.encode("护工模板.xlsx","UTF8")); 
        	headers.setContentType(MediaType.valueOf("application/vnd.ms-excel"));   
        	return new ResponseEntity<byte[]>(fileResponse.bodyAsBytes(),
                    headers, HttpStatus.OK);
		} catch (IOException e) {
			throw new RuntimeException("模板文件下载失败" + e);
		}
	}

	/**
	 * 批量导入护工基本信息
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/importNurseExcel")
	public SysResult importNurseExcel(@RequestParam(value = "excel") MultipartFile file) throws Exception {
		// 设置医院
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		Map<String, String> map = new HashMap<>();
		map.put("teamId", user.getHospitalId());
		String url = nurseServiceAddress + "/nurse/importNurseExcel";
		return JsoupUtils.doPostFileRequestToSysResult(url, map, file, "excel");
	}

	/**
	 * 批量导入护工图片信息
	 * 
	 * @throws Exception
	 */
	@RequestMapping("/importNursePictureZip")
	public SysResult importNursePictureZip(@RequestParam(value = "zip") MultipartFile file) throws Exception {
		// 当前登录人
		User user = LocalManager.getVal(LocalManagerType.USER_WEB);
		Map<String, String> map = new HashMap<>();
		map.put("teamId", user.getHospitalId());
		String url = nurseServiceAddress + "/nurse/importNurseExcel";
		return JsoupUtils.doPostFileRequestToSysResult(url, map, file, "zip");
	}

	/**
	 * 健康证延期提醒列表
	 * 
	 * @throws IOException
	 */
	@RequestMapping("/list-healthcert")
	public SysResult listHealthCert(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto)
			throws IOException {
		// 当前登录人信息
		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoRequestDto.setTeamId(courrentUser.getHospitalId());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/list-healthcert",
				nurseWorkerInfoRequestDto);
	}

	/**
	 * 健康证延期提醒--导出Excel
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/export-healthcert-excel")
	public void exportHealthCertExcel(NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto, HttpServletResponse response)
			throws Exception {
		OutputStream toClient = null;
		try {
			// 当前登录人信息
			User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
			nurseWorkerInfoRequestDto.setTeamId(courrentUser.getHospitalId());
			Response fileResponse = JsoupUtils.doPostFileResponse(
					nurseServiceAddress + "/nurse/export-healthcert-excel", nurseWorkerInfoRequestDto);
			String finalFileName = URLEncoder.encode("健康证延期提醒" + TimeUtils.getTime(TimeType.yyyyMMddHHmmssSSS) + ".xls",
					"UTF8");
			response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
			toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(fileResponse.bodyAsBytes());
		} catch (IOException e) {
			throw new RuntimeException("文件下载失败" + e);
		} finally {
			try {
				toClient.flush();
				toClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 修改到期日
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/modify-health-date")
	public SysResult modifyHealthDate(@RequestBody NurseWorkerInfoDto nurseWorkerInfoDto) throws IOException {
		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoDto.setHospital(courrentUser.getHospitalId());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/modify-health-date", nurseWorkerInfoDto);
	}

	/**
	 * 提醒补办
	 * 
	 * @param nurseWorkerInfoDto
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/remind")
	public SysResult remind(@RequestBody NurseWorkerInfoDto nurseWorkerInfoDto) throws IOException {
		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoDto.setHospital(courrentUser.getHospitalId());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/remind", nurseWorkerInfoDto);
	}

	/**
	 * 批量提醒
	 * 
	 * @param nurseWorkerInfoRequestDto
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/batch-remind")
	public SysResult batchRemind(@RequestBody NurseWorkerInfoRequestDto nurseWorkerInfoRequestDto) throws IOException {
		// 当前登录人信息
		User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
		nurseWorkerInfoRequestDto.setTeamId(courrentUser.getHospitalId());
		return JsoupUtils.postConnectToSysResult(nurseServiceAddress + "/nurse/batch-remind",
				nurseWorkerInfoRequestDto);
	}

	/**
	 * 下载文档pdf
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download-pdf")
	public void downloadPdf(Integer[] ids, HttpServletResponse response) throws Exception {
		OutputStream toClient = null;
		try {
			// 当前登录人信息
			User courrentUser = LocalManager.getVal(LocalManagerType.USER_WEB);
			Map<String, Object> map = new HashMap<>();
			map.put("teamId", courrentUser.getHospitalId());
			map.put("ids", new ArrayList<Integer>(Arrays.asList(ids)));
			Response fileResponse = JsoupUtils.doPostFileResponse(
					nurseServiceAddress + "/nurse/download-pdf", map);
			String finalFileName = URLEncoder.encode("护理员档案.pdf", "UTF8");
			response.addHeader("Content-Disposition", "attachment;filename=" + finalFileName);
			toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(fileResponse.bodyAsBytes());
		} catch (IOException e) {
			throw new RuntimeException("文件下载失败" + e);
		} finally {
			try {
				toClient.flush();
				toClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

}
